何泽弘

何泽弘的博客

这是一个中二半吊子码农分享学习经验和生活的网站...

常见的 CSS 实现块元素居中方案


常见的 CSS 实现块元素居中方案

1、定位 + 负外边距

使用 position: absolute ,设置 lefttopmargin-leftmargin-top 的属性。这种方法基本浏览器都能够兼容,不足之处就是需要固定宽高。

/* 父元素 */
.parent{
    position: relative;
}

/* 需要居中的元素 */
.parent .child{
    position: absolute;
    width: 200px; /* 宽度 */
    height: 200px; /* 高度 */
    top: 50%;
    left: 50%;
    margin-top: -100px; /* -50%高度 */
    margin-left: -100px; /* -50%宽度 */
}

2、定位 + 自动外边距

使用 position: absolute ,设置 top: 0right: 0bottom: 0left: 0margin: auto 的属性。和上面一个方法一样,不足之处就是需要固定宽高。

/* 父元素 */
.parent{
    position:relative;
}
/* 需要居中的元素 */
.parent .child{
    position: absolute;
    width: 200px; /* 宽度 */
    height: 200px; /* 高度 */
    top: 0; /* 设置为 0 */
    right: 0; /* 设置为 0 */
    bottom: 0; /* 设置为 0 */
    left: 0; /* 设置为 0 */
    margin: auto; /* 自动外边距 */
}

3、定位 + 2D平移转换

这个方法可以不需要设定固定的宽高,在移动端用的会比较多,在移动端css3兼容的比较好

/* 父元素 */
.parent{
    position: relative;
}

/* 需要居中的元素 */
.parent .child{
    position: absolute;
    top: 50%;
    left: 50%;
    transform:translate(-50%, -50%);
}

Autoprefixer - CSS prefixes:

/* 父元素 */
.parent{
    position: relative;
}

/* 需要居中的元素 */
.parent .child{
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform:translate(-50%, -50%);
       -moz-transform:translate(-50%, -50%);
        -ms-transform:translate(-50%, -50%);
         -o-transform:translate(-50%, -50%);
            transform:translate(-50%, -50%);
}

4、flex 居中

这个方法可以不需要设定固定的宽高,在移动端用的会比较多,在移动端css3兼容的比较好

/* 父元素 */
.parent{
    display: flex;
    justify-content: center;
    align-items: center;
}

Autoprefixer - CSS prefixes:

/* 父元素 */
.parent{
    display: -webkit-box;
    display: -webkit-flex;
    display: -moz-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: center;
    -webkit-justify-content: center;
    -moz-box-pack: center;
    -ms-flex-pack: center;
            justify-content: center;
    -webkit-box-align: center;
    -webkit-align-items: center;
    -moz-box-align: center;
    -ms-flex-align: center;
            align-items: center;
}

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请狠狠点击下面的